package com.example.a2032.Utils;

import android.app.Activity;
import android.app.Application;
import android.app.backup.BackupManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.PowerManager;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.example.a2032.BuildConfig;
import com.example.a2032.activity.TempUnitSettingActivity;
import com.example.a2032.db.DataDbHelper;
import com.example.a2032.entity.PPGMeasureData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

import static android.content.Context.TELEPHONY_SERVICE;
import static com.example.a2032.Utils.ResolveUtil.getNumberFormat;

public class Utils {
    private static final String TAG = "Utils";

    public static int getImageId(Context context, String imageId) {

        return context.getResources().getIdentifier(imageId, "mipmap", context.getPackageName());
    }

    public static String getFormatIntString(int value) {
        return String.format("%02d", value);
    }

    public static String getFormatDateString(int month, int day, String split) {
        return getFormatIntString(month) + split + getFormatIntString(day);
    }

    public static String getFormatTimeString(int hour, int minute) {
        return getFormatDateString(hour, minute, ":");
    }

    public static int[] getResourcesImageArray(Context context, int arrayId) {
        TypedArray ar = context.getResources().obtainTypedArray(arrayId);
        final int len = ar.length();
        final int[] resIds = new int[len];
        for (int i = 0; i < len; i++) {
            resIds[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
        return resIds;
    }

    public static int[] getAdapterImageArray(RecyclerView.ViewHolder holder, int arrayId) {
        Context context = holder.itemView.getContext();
        return getResourcesImageArray(context, arrayId);
    }

    public static Resources getAdapterResources(RecyclerView.ViewHolder holder) {
        return holder.itemView.getContext().getResources();
    }

    public static void setProperty(String key, String value) {
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method set = c.getMethod("set", String.class, String.class);
            set.invoke(c, key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getProperty(String key, String defaultValue) {
        String value = defaultValue;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) (get.invoke(c, key, defaultValue));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return value;
        }
    }

    public static String getShowMeasureValue(int measureValue) {
        return measureValue == 0 ? "--" : String.valueOf(measureValue);
    }

    public static void startVibrato(Context context) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Activity.VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    public static void startVibrato(Context context, long time) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Activity.VIBRATOR_SERVICE);
        vibrator.vibrate(time);
    }

    public static String getFormatTime(String format, long time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(new Date(time));
    }

    public static String getTodayTimeString() {
        return getFormatTime("yyyy.MM.dd", System.currentTimeMillis());
    }

    public static String getCurrentTimeNoSecond() {
        return getFormatTime("yyyy.MM.dd HH:mm", System.currentTimeMillis());
    }

    public static int getSleepLevel(float data) {
        int level = 2;
        if (data >= 0 && data <= 2) {//深睡
            level = 0;
        } else if (data > 2 && data <= 8f) {//浅睡
            level = 1;
        } else if (data > 8f && data <= 20f) {//rem
            level = 3;
        } else {//清醒
            level = 2;
        }
        return level;
    }

    public static String getIMEI(Context context) {
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                imei = tm.getDeviceId();
            } else {
                Method method = tm.getClass().getMethod("getImei");
                imei = (String) method.invoke(tm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i(TAG, "getIMEI: " + imei);
        return imei;
    }

    public static String getAppVersion() {
        return BuildConfig.VERSION_NAME;
    }

    public static String getWatchId() {

        return SharedPreferenceUtils.getString(SharedPreferenceUtils.watchId, "");
    }

    public static String getPhone(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        return telephonyManager.getLine1Number();
    }

    public static void wakeUpAndUnlock(Context context) {

        //获取电源管理器对象
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.SCREEN_DIM_WAKE_LOCK, pm.getClass().toString());
        //点亮屏幕
        wl.acquire();
        //释放
        wl.release();
    }

    public static MediaPlayer startPlayAssetRing(Context context, String fileName) {
        AssetManager assetManager = context.getAssets();
        MediaPlayer mediaPlayer = null;
        try {
            AssetFileDescriptor assetFileDescriptor = assetManager.openFd(fileName);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(),
                    assetFileDescriptor.getLength());
            mediaPlayer.prepare();
            mediaPlayer.setLooping(true);
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaPlayer;
    }

    public static void startMeasureTimer(long maxMeasureTime, Observer observer) {
        //Observable.timer(maxMeasureTime, TimeUnit.MINUTES).compose(SchedulersTransformer.io2MainObservable()).subscribe(observer);
        startMeasureTimer(maxMeasureTime, TimeUnit.MINUTES, observer);
    }

    public static void startMeasureTimer(long maxMeasureTime, TimeUnit unit, Observer observer) {
        Observable.timer(maxMeasureTime, unit).compose(SchedulersTransformer.io2MainObservable()).subscribe(observer);
    }

    /**
     * 关机，需要系统权限
     *
     * @param context
     */
    public static void shutdown(Context context) {
        try {
            Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
            intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
            //其中false换成true,会弹出是否关机的确认窗口
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Log.i(TAG, "shutdown: " + e.getLocalizedMessage());
        }

    }

    public static void startTempMeasureTimer(CompositeDisposable compositeDisposable) {
        if (compositeDisposable.size() == 1) return;
        Observable.interval(0, 2, TimeUnit.SECONDS).compose(SchedulersTransformer.<Long>io2MainObservable()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
            }

            @Override
            public void onNext(Long aLong) {
                Log.i(TAG, "Reconnect onNext: " + aLong);

                SerialPortUtil.getInstance().sendSerialPort(BleSdk.getTempData());
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    public static void saveBPData(Context context, PPGMeasureData ppgMeasureData, String from) {
        //app开启的暂时不保存（app开启的服务器那边会保存，如果本地也保存会出现时间不一致）
        if (!TextUtils.isEmpty(from)) return;
        String date = DateUtils.getDefaultDate(new Date());
        ppgMeasureData.setDate(date);
        DataDbHelper.getInstance(context).getPPGDataDao().insert(ppgMeasureData);
    }

    static long lastClickTime = 0;
    static int lastClickId = 0;

    public static boolean isFastClick(View view) {
        boolean isFastClick = false;
        if (view.getId() == lastClickId) {
            isFastClick = System.currentTimeMillis() - lastClickTime < 1000;
        } else {
            isFastClick = false;
        }
        lastClickId = view.getId();
        lastClickTime = System.currentTimeMillis();
        return isFastClick;
    }

    public static String getRootPath(Context context) {
        String rootPath = context.getExternalFilesDir("").getAbsolutePath();
        return rootPath;
    }

    public static String getFirmwarePath(Context context) {
        String rootPath = getRootPath(context);
        File file = new File(rootPath, "update");
        return file.getAbsolutePath();
    }

    public static void writeToDisk(Context context, String fileName, ResponseBody responseBody) throws IOException {
        Log.i(TAG, "writeToDisk: ");
        String rootPath = getRootPath(context);
        File file = new File(rootPath, "update");
        if (!file.exists()) file.mkdirs();
        File languageFile = new File(file, fileName);
        if (!languageFile.exists()) languageFile.createNewFile();
        if (languageFile.exists() && languageFile.length() == responseBody.contentLength()) return;
        byte[] buffer = new byte[1024 * 8];
        int len;
        FileOutputStream out = new FileOutputStream(languageFile);
        InputStream in = responseBody.byteStream();
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();


    }

    public static String getShowTemp(float tempValue) {
        NumberFormat numberFormat = getNumberFormat(1);
        int tempUnit = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_TempUnit,
                SharedPreferenceUtils.tempUnitC);//默认摄氏度
        String showTemp = tempUnit == SharedPreferenceUtils.tempUnitF ? numberFormat.format(1.8f * tempValue + 32) : numberFormat.format(tempValue);
        return showTemp;
    }

    public static String getShowTempUnit() {

        int tempUnit = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_TempUnit,
                SharedPreferenceUtils.tempUnitC);//默认摄氏度
        String tempUnitText = tempUnit == SharedPreferenceUtils.tempUnitF ? "℉" : "℃";
        return tempUnitText;
    }

    public static void changeSystemLanguage(Locale locale) {
        try {
            Class classActivityManagerNative = Class.forName("android.app.ActivityManagerNative");
            Method getDefault = classActivityManagerNative.getDeclaredMethod("getDefault");
            Object objIActivityManager = getDefault.invoke(classActivityManagerNative);
            Class classIActivityManager = Class.forName("android.app.IActivityManager");
            Method getConfiguration = classIActivityManager.getDeclaredMethod("getConfiguration");
            Configuration config = (Configuration) getConfiguration.invoke(objIActivityManager);
            config.setLocale(locale);
            Class clzConfig = Class
                    .forName("android.content.res.Configuration");
            java.lang.reflect.Field userSetLocale = clzConfig
                    .getField("userSetLocale");
            userSetLocale.set(config, true);
            Class[] clzParams = {Configuration.class};
            Method updateConfiguration = classIActivityManager.getDeclaredMethod("updateConfiguration", clzParams);
            updateConfiguration.invoke(objIActivityManager, config);
            BackupManager.dataChanged("com.android.providers.settings");
        } catch (Exception e) {
            Log.i(TAG, "changeSystemLanguage: " + e.getLocalizedMessage());
            e.printStackTrace();
        }
    }

    public static void changeAppLanguage(Context context) {
        String sta = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_Language);
        Resources resources = context.getResources();
        Configuration conf = resources.getConfiguration();
        if (TextUtils.isEmpty(sta)||isSystemApp(context)) return;
        Locale myLocale;
        if (sta.contains("_")) {
            String[] stas = sta.split("_");
            myLocale = new Locale(stas[0], stas[1]);
        } else {
            myLocale = new Locale(sta);
        }
        DisplayMetrics dm = resources.getDisplayMetrics();
        conf.locale = myLocale;
        resources.updateConfiguration(conf, dm);
    }

    public static void changeLanguage(Context context, Locale locale) {
      //  if (isSystemApp(context)) {
        changeSystemLanguage(locale);
//        } else {
           //changeAppLanguage(context);
//        }
    }

    public static boolean isSystemApp(Context context) {
        String pkgName = context.getPackageName();
        boolean isSystemApp = false;
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(pkgName, 0);
        } catch (Throwable t) {
            Log.w(TAG, t.getMessage(), t);
        }
        // 是系统中已安装的应用
        if (pi != null) {
            boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
            isSystemApp = isSysApp;
        }
        return isSystemApp;
    }

    public static int getSetLanguagePosition(String[]languageCodeArrays){
        int position=-1;
        String sta = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_Language);
        if(TextUtils.isEmpty(sta))return position;
        for(int i=0;i<languageCodeArrays.length;i++){
            if(sta.equals(languageCodeArrays[i])){
                position=i;
                break;
            }
        }

        return position;
    }
}
